<template>
	<dt-main-body v-model="labelPosition">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>商城管理</el-breadcrumb-item>
				<el-breadcrumb-item>编辑优惠券</el-breadcrumb-item>
			</el-breadcrumb>
		</div>

		<div class="content-box">
			<el-form ref="editForm" :model="model" :rules="rules" :label-position="labelPosition" label-width="120px">
				<el-tabs v-model="activeName" type="card">
					<el-tab-pane label="基本信息" name="info">
						<div class="tab-content">
							<el-form-item prop="merchantId" label="所属商户">
								<dt-merchant-select v-model="model.merchantId" placeholder="请选择..."></dt-merchant-select>
							</el-form-item>
							<el-form-item prop="useType" label="适用范围">
								<el-radio-group v-model="model.useType">
									<el-radio-button :label="0">店铺券</el-radio-button>
									<el-radio-button :label="1">商品券</el-radio-button>
								</el-radio-group>
							</el-form-item>
							<el-form-item label="关联商品" v-if="model.useType===1">
								<dt-goods-multiple v-model="goodsData"></dt-goods-multiple>
							</el-form-item>
							<el-form-item prop="title" label="标题名称">
								<el-input v-model="model.title" placeholder="必填，128字符内"></el-input>
							</el-form-item>
							<el-form-item prop="amount" label="优惠金额">
								<el-input v-model="model.amount" placeholder="必填，优惠券抵扣金额">
									<template slot="append">
										元
									</template>
								</el-input>
							</el-form-item>
							<el-form-item prop="minAmount" label="消费门槛">
								<el-input v-model="model.minAmount" placeholder="必填，订单满N元可用">
									<template slot="append">
										元
									</template>
								</el-input>
							</el-form-item>
							<el-form-item prop="point" label="兑换积分">
								<el-input v-model="model.point" placeholder="必填，兑换优惠券积分">
									<template slot="append">
										分
									</template>
								</el-input>
							</el-form-item>
							<el-form-item prop="publishCount" label="发行数量">
								<el-input v-model="model.publishCount" placeholder="优惠券的总数量">
									<template slot="append">
										张
									</template>
								</el-input>
							</el-form-item>
							<el-form-item prop="enableTime" label="领取时间">
								<el-date-picker v-model="model.enableTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="领取时间"></el-date-picker>
							</el-form-item>
							<el-form-item prop="startTime" label="使用时间">
								<el-date-picker v-model="model.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始时间"></el-date-picker>
							</el-form-item>
							<el-form-item prop="endTime" label="有效期至">
								<el-date-picker v-model="model.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结束时间"></el-date-picker>
							</el-form-item>
							<el-form-item label="使用情况" v-if="model.id>0">
								已领取 {{model.receiveCount}} 张，已使用 {{model.useCount}} 张
							</el-form-item>
							<el-form-item label="创建时间" v-if="model.id>0">
								{{model.addBy}} {{model.addTime}}
							</el-form-item>
							<el-form-item label="最后更新" v-if="model.id>0&&model.updateTime">
								{{model.updateBy}} {{model.updateTime}}
							</el-form-item>
						</div>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</div>
		
		<div class="footer-box">
			<div class="footer-btn">
				<el-button type="primary" :loading="loading" @click="submitForm">确认保存</el-button>
				<el-button plain @click="$common.back()">返回上一页</el-button>
			</div>
		</div>
	</dt-main-body>
</template>

<script>
	import DtMerchantSelect from '../../../components/DtMerchantSelect.vue'
	import DtGoodsMultiple from '../../../components/DtGoodsMultiple.vue'
	
	export default {
		components: {
			DtMerchantSelect,
			DtGoodsMultiple,
		},
		props: {
			id: 0
		},
		data() {
			return {
				activeName: 'info', //当前选项卡
				labelPosition: 'right', //表单对齐方式
				loading: false,
				goodsData: [],//已选商品列表
				model: {
					id: 0,
					merchantId: null,
					useType: 0,
					title: null,
					amount: 0,
					minAmount: 0,
					point: 0,
					publishCount: null,
					useCount: 0,
					receiveCount: 0,
					enableTime: null,
					startTime: null,
					endTime: null,
					addBy: null,
					addTime: null,
					updateBy: null,
					updateTime: null,
					goodsRelations: []
				},
				rules: {
					merchantId: [
						{ required: true, message: '请选择所属商户', trigger: 'change' }
					],
					title: [
						{ required: true, message: '请输入优惠券名称', trigger: 'blur' }
					],
					useType: [
						{ required: true, message: '请选择优惠券使用范围', trigger: 'change' }
					],
					amount: [
						{ required: true, message: '请输入优惠券金额', trigger: 'blur' },
						{ pattern: /^(([1-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/, message: '请输入正确金额，可保留两位小数', trigger: 'blur' }
					],
					minAmount: [
						{ required: true, message: '请输入最低消费门槛', trigger: 'blur' },
						{ pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确金额，可保留两位小数', trigger: 'blur' }
					],
					point: [
						{ required: true, message: '请输入兑换优惠券积分', trigger: 'blur' },
						{ pattern: /^-?[0-9]\d*$/, message: '兑换积分只能为整数', trigger: 'blur' }
					],
					publishCount: [
						{ required: true, message: '请输入优惠券发行数量', trigger: 'blur' },
						{ pattern: /^-?[1-9]\d*$/, message: '优惠券数量只能为整数', trigger: 'blur' }
					],
					enableTime: [
						{ required: true, message: '请选择可领取时间', trigger: 'change' }
					],
					startTime: [
						{ required: true, message: '请选择可使用时间', trigger: 'change' }
					],
					endTime: [
						{ required: true, message: '请选择过期时间', trigger: 'change' }
					]
				}
			}
		},
		methods: {
			//初始化数据
			initData() {
				let _this = this; //当前页面
				if (_this.id) {
					_this.$api.request({
						url: '/admin/shop/coupon/' + _this.id,
						loading: true,
						success(res) {
							//赋值给model
							Object.keys(_this.model).forEach(key => { _this.model[key] = res.data[key] });
							//给商品设置赋值
							if (_this.model.goodsRelations) {
								_this.model.goodsRelations.map(item => {
									_this.goodsData.push(item.goods);
								})
							}
						}
					});
				}
			},
			//提交表单
			submitForm() {
				let _this = this; //当前页面
				//多个表单验证
				const f1 = new Promise((resolve, reject) => {
					_this.$refs['editForm'].validate((valid) => {
						if (valid) resolve()
					});
				});
				Promise.all([f1]).then(() => {
					//检查及组合参数
					if (_this.model.useType == 1) {
						if (_this.goodsData.length === 0) {
							_this.$message({ type: 'warning', message: '错误提示：请选择关联商品' });
							return false;
						}
						//商品取值
						let goodsRelations = [];
						_this.goodsData.map(function (item) {
							let modelt = {
								id: 0,
								couponId: _this.model.id,
								goodsId: item.id
							}
							//遍历Model已有值，防止ID丢失
							_this.model.goodsRelations.map((row) => {
								if (modelt.goodsId === row.goodsId) {
									modelt.id = row.id;
								}
							});
							goodsRelations.push(modelt);
						});
						_this.model.goodsRelations = goodsRelations;
					} else {
						_this.model.goodsRelations = [];
					}
					
					//提交表单,Id大于0则修改，否则添加
					if (_this.model.id > 0) {
						_this.$api.request({
							method: 'put',
							url: '/admin/shop/coupon/' + _this.model.id,
							data: _this.model,
							successMsg: '优惠券修改成功',
							beforeSend() {
								_this.loading = true;
							},
							success(res) {
								//可跳转加列表页
								_this.$common.linkUrl('/shop/coupon/list');
							},
							complete() {
								_this.loading = false
							}
						});
					} else {
						_this.$api.request({
							method: 'post',
							url: '/admin/shop/coupon',
							data: _this.model,
							successMsg: '新增优惠券已成功',
							beforeSend() {
								_this.loading = true;
							},
							success(res) {
								//重置表单
								_this.$refs['editForm'].resetFields();
							},
							complete() {
								_this.loading = false
							}
						});
					}
				})
			},
			
			
		},
		created() {
			//初始化数据
			this.initData();
		}
	}
</script>